package com.gexin.controller.xapp.agent;

import com.gexin.model.agent.*;
import org.apache.commons.beanutils.BeanUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.gexin.common.AppGlobal;
import com.gexin.common.kusy.KusyApi;
import com.gexin.common.kusy.KusyUtil;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.*;
import com.gexin.core.interceptor.XAppSafeInterceptor;
import com.gexin.core.web.AppController;
import com.gexin.core.web.XAppController;
import com.gexin.model.order.Order;
import com.gexin.model.order.OrderItem;
import com.gexin.model.order.OrderPresale;
import com.gexin.model.product.ProductSku;
import com.gexin.model.product.Products;
import com.gexin.model.system.*;
import com.gexin.model.template.TemplateArea;
import com.gexin.model.user.UserCoupon;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.agent.AgentService;
import com.gexin.service.order.OrderInvoiceService;
import com.gexin.service.order.OrderService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import java.math.BigDecimal;
import java.util.*;

/**
 * 代理商小程序接口
 */
@Before(XAppSafeInterceptor.class)//统一错误拦截
@ControllerBind(controllerKey = "/xapp/agent")
public class AgentController extends AppController {

	/**
	 * 给区域代理商添加补贴
	 */
	public  ApiResponse areaAddDiscount(){
		String id = getPara("id");
		String price = getPara("price");
		String orderId = getPara("orderId");
		ApiResponse apiResponse = AgentService.dao.areaAddSubsidy(id, price,orderId);
		return apiResponse;
	}





	@Clear
	public void shopTypeList(){
		List<AdminDict> shopType = AdminDict.dao.cache_findDictByKey("SHOP_TYPE");
		renderJson(shopType);
	}

	/**
	 * 获取所有的城市
	 */
	@Clear
	public void addrList(){
		List<AddrCities> all = AddrCities.dao.findAll();
		success(all);
	}
	@Clear
	public void proList(){
		List<AddrProvinces> provinces = AddrProvinces.dao.findAll();
		success(provinces);
	}
	@Clear
	public void cityList(){
		String city_id = getPara("province_id");
		List<AddrCities> byProvinceId = AddrCities.dao.findByProvinceId(city_id);
		success(byProvinceId);
	}
	@Clear
	public void areaList(){
		String cityId = getPara("city_id");
		AddrCities addrCities = AddrCities.dao.findByCityId(cityId);
		if(addrCities==null){
			fail("查询不到该城市");
			return;
		}
		if(AddrCities.TYPE_OPEN_FAIL.equals(addrCities.getIsArea())){
			fail("该城市没有开启区域代理!");
			return;
		}
		List<AddrAreas> areasList = AddrAreas.dao.getAreasByCityId(cityId);
		success(areasList);
	}


	/**
	 * 保存代理商
	 * /xapp/agent/save
	 */
	public void save(){
		Agent agent = getModel(Agent.class , "agent");
		WeixinUser user = getAuthUser();
		Integer type = getParaToInt("type");
		String code = getPara("code");
		boolean checkCode = MessageUtils.CheckCode(agent.getAgentPhone() , code,MessageUtils.loginId);
		if(!checkCode){
			fail("验证码错误!");
			return;
		}
		MessageUtils.delCode(agent.getAgentPhone(),MessageUtils.loginId);
		if (type==null){
			fail("代理商类型不能为null!");
			return;
		}
		if (getAuthUser()==null){
			fail("用户未授权!");
			return;
		}
		Agent agent1 = Agent.dao.findInfoByUserIdAndStatus(user.getId(),Agent.STATUS_SUCCESS);
		if(agent1!=null){
			fail("该用户已是代理商!");
			return;
		}
		Agent agent2 = Agent.dao.findInfoByUserId(user.getId());
		if(agent2!=null){
			fail("已提交过代理商申请或该用户已经是代理商!请勿重复提交");
			return;
		}
		if(Agent.TYPE_NORM.equals(type)||Agent.TYPE_TEYUE.equals(type)){
			agent.setType(type);
			ApiResponse apiResponse = AgentService.dao.saveNormalAgent(agent , user);
			renderJson(apiResponse);
		}else if(Agent.TYPE_AREA==type){
			String cityStr = getPara("cities");
			if(StringUtil.isBlank(cityStr)){
				fail("代理城市必填!");
				return;
			}
			String[] citys = cityStr.split(",");
			String areaStr = getPara("areaes");
			if(StringUtil.isBlank(areaStr)){
				fail("代理城市必填!");
				return;
			}
			String[] areaes = areaStr.split(",");
			agent.setType(type);
			ApiResponse apiResponse = AgentService.dao.saveAreaAgent(agent , citys,areaes,user.getId());
			renderJson(apiResponse);
		}else if (Agent.TYPE_ER==type){
			agent.setType(type);
			ApiResponse apiResponse = AgentService.dao.saveErJiAgent(agent , user);
			renderJson(apiResponse);
		}

	}

	/**
	 * 代理商详情
	 */
	public void info(){
		WeixinUser user = getAuthUser();
		if(user==null){
			fail("用户未登录");
			return;
		}
		ApiResponse byUser = AgentService.dao.findByUser(user);
		renderJson(byUser);
	}
	/**
	 * 代理商详情
	 */
	public void findById()  {
		String agentId = getPara("agent_id");
		ApiResponse byUser = AgentService.dao.findInfoByAgentId(agentId);
 		renderJson(byUser);
	}


	/**
	 * 编辑
	 */
	public void editor(){
		Integer userId = getAuthUserId();
		Agent agent = AgentService.dao.findInfoByOpenId(userId);
		renderJson(agent);
	}


	/***
	 * 提交提现申请或直接提现
	 * /xapp/agent/withdrawal
	 */
	public void withdrawal(){
		AdminConfig sysConfig = AdminConfig.dao.getSysConfig();
		String price = getPara("price");
		WeixinUser authUser = getAuthUser();
		Integer userId = authUser.getId();
		String bankName = getPara("bank_name");
		String bankUserName = getPara("bank_user_name");
		String bankNum = getPara("bank_num");
		if(sysConfig.getOpenAutoWithdrawal()!=null&&sysConfig.getOpenAutoWithdrawal()==1){
			ApiResponse apiResponse = AgentService.dao.AutoWithdrawal(authUser , price);
			renderJson(apiResponse);
		}else{
			ApiResponse response = AgentService.dao.withdrawal(price , userId,bankName,bankUserName,bankNum);
			renderJson(response);
		}

	}





	/**
	 * 账户管理（金额操作记录）
	 * /xapp/agent/accountLog
	 */
	public void accountLog(){
		String agentId = getPara("agent_id");
		Integer state = getParaToInt("state");
		if(StringUtil.isBlank(agentId)){
			fail("代理商id不能为空!");
			return;
		}
		if(state==null){
			fail("提现或充值状态不能为空!");
			return;
		}
		Page<AgentAccountLog> accountLogList = AgentService.dao.findAccountLogList(getPageIndex() , getPageSize() , agentId , state);
		renderJson(accountLogList);
	}

	/**
	 * 获取账户总记录
	 * /xapp/agent/accountLogAll
	 */
	public void accountLogAll(){
		String agentId = getPara("agent_id");
		if(StringUtil.isBlank(agentId)){
			fail("代理商id不能为空!");
			return;
		}
		ApiResponse apiResponse = AgentService.dao.accountLogAll(agentId);
		renderJson(apiResponse);
	}

	/**
	 * 获取验证码
	 * /xapp/agent/findcode
	 */
	public void findcode(){
		String phone = getPara("phone");
		if(StringUtil.isBlank(phone)){
			fail("电话号码不能为null!");
			return;
		}
		if(phone.length()!=11){
			fail("电话号码长度错误!");
			return;
		}
		Random rand = new Random();
		String code = StringUtil.fillString(rand.nextInt(10000)+"", "0", 4, StringUtil.FILL_TYPE_LEFT);
		ApiResponse apiResponse = MessageUtils.SendCode_New(phone , code , MessageUtils.loginId , getRequest());
		renderJson(apiResponse);
	}

	/**
	 *	代理商订单列表
	 */
	public void agentOrderList(){
		Integer agentId = getParaToInt("agent_id");
		if (agentId==null){
			fail("代理商id不能为null!");
			return;
		}
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String state = getPara("state");
		String type = getPara("type");
		String cityId = getPara("city_id");

		Page<Order> agentOrders = OrderService.dao.findAgentOrders(agentId,getPageIndex(),getPageSize(),startTime,endTime,state,type,cityId);
		renderJson(agentOrders);
	}


	/**
	 *	代理商订单列表
	 */
	public void erAgentOrderList(){
		Integer agentId = getParaToInt("agent_id");
		if (agentId==null){
			fail("代理商id不能为null!");
			return;
		}
		String startTime = getPara("startTime");
		String endTime = getPara("endTime");
		String state = getPara("state");
		String type = getPara("type");//类型 0是直客订单  1是自己的订单 空是所有的

		Page<Order> agentOrders = OrderService.dao.findErJiAgentOrders(agentId,getPageIndex(),getPageSize(),startTime,endTime,state,type);
		renderJson(agentOrders);
	}


	/**
	 * 获取代理商商品列表
	 *  /xapp/agent/agentProduct 参数 agentCityId  type_id
	 */
	public void agentProductList(){
		Integer typeId = getParaToInt("type_id");
		List<Products> productsList = Products.dao.findByAttrType(typeId , getPageIndex());
		String agentCityId = getPara("agentCityId");
		AgentCity agentCity = AgentCity.dao.findById(agentCityId);
		AgentLevel agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
		for (Products products : productsList) {
			BigDecimal agentPrice = products.getPrice().multiply(agentLevel.getDiscount());
			products.put("agentPrice",agentPrice);
		}
		renderJson(productsList);
	}


	/**
	 * 获取所有的代理城市
	 *  /xapp/agent/agentCityList 参数 agent_id
	 */
	public void agentCityList(){
		Integer agentId = getParaToInt("agent_id");
		if(agentId==null){
			fail("代理商id不能为null!");
			return;
		}
		List<AgentCity> cities = AgentCity.dao.findByAgentId(agentId,AgentCity.STATUS_SUCCESS);
		renderJson(cities);
	}

	/**
	 * 推送列表
	 */
	public void pushList(){
		String agentId = getPara("agent_id");
		if(StringUtil.isBlank(agentId)){
			fail("代理商id不能为null!");
			return;
		}
		Agent agent = Agent.dao.findById(agentId);
		if(agent==null){
			fail("代理商不存在!");
			return;
		}
		Page<WeixinUser> userPage = WeixinUser.dao.findByExtensionId(getPageIndex() , getPageSize() , agentId);
		agent.put("users",userPage);
		renderJson(agent);
	}

	/**
	 * 保存二级代理商
	 */
	public void saveErJiAgent(){
		String name = getPara("name");
		String phone = getPara("phone");
		Integer parentId = getParaToInt("parent_id");
		if (getAuthUser()==null){
			fail("用户未授权!");
		}
		String discountStr = getPara("discount");
		BigDecimal discount ;
		try{
			discount = new BigDecimal(discountStr);
		}catch (NumberFormatException e){
			fail("折扣格式错误");
		}
		Integer authUserId = getAuthUserId();
		Agent agent = Agent.dao.findInfoByUserId(authUserId);
		if(!Agent.TYPE_ER.equals(agent.getType())){
			fail("代理商类型错误!不能添加!");
			return;
		}
		ApiResponse apiResponse = AgentService.dao.saveByErjiAgent(name , phone , parentId , authUserId , agent);
		renderJson(apiResponse);
	}

	/**
	 * 查询该经销商下的所有特约经销商
	 */
	public void findAuthorizedDealer(){
		Integer agentId = getParaToInt("agent_id");
		if (agentId==null){
			fail("代理商id不能为null!");
			return;
		}
		ApiResponse response = AgentService.dao.findAuthorizedDealer(getPageIndex() , getPageSize() , agentId);
		renderJson(response);
	}



	/**
	 * 审核特约代理商
	 */
	public void auditAuthorizedDealer(){
		String id = getPara("id");
		if(StringUtil.isBlank(id)){
			fail("被代理商id不能为空!");
			return;
		}
		Integer status = getParaToInt("status");
		if(status==null){
			fail("状态不能为空!");
			return;
		}
		if(status==1){
			String discount = getPara("discount");
			if(StringUtil.isBlank(discount)){
				fail("折扣不能为空!");
			}



//			ApiResponse apiResponse = AgentService.dao.auditTeYueAgent(id , status , discount , getAuthUserId());
//			if(apiResponse.isState()){
//				Agent agent = Agent.dao.findById(id);
//				WeixinUser user = WeixinUser.dao.findById(agent.getUserId());
//				String unionid = user.getUnionid();
//				WeixinUser weixinUser = WeixinUser.dao.findGZHUserByUnionId(unionid);
//				if (weixinUser != null && weixinUser.getId() != null) {
//					Map<String, String> map = new HashMap<>();
//					String first = "";
////					/**类型 普通代理类型*/
////					public static final Integer TYPE_NORM = 1;
////					/**类型 区域代理类型*/
////					public static final Integer TYPE_AREA = 0;
////					/**类型 二级代理商类型*/
////					public static final Integer TYPE_ER = 2;
////					/**类型 特约代理商类型*/
////					public static final Integer TYPE_TEYUE = 3;
//					switch (agent.getType()){
//						case 0:
//							first = "您已成功注册中科易购 区域  经销商，中科易购将竭诚为您服务。";
//							break;
//						case 1:
//							first = "您已成功注册中科易购 普通代理，中科易购将竭诚为您服务。";
//							break;
//						case 2:
//							first = "您已成功注册中科易购 二级代理商，中科易购将竭诚为您服务。";
//							break;
//						case 3:
//							first = "您已成功注册中科易购 特约代理商，中科易购将竭诚为您服务。";
//							break;
//						default:
//							first="";
//							break;
//					}
//					map.put("first",first);
//					map.put("keyword1",agent.getAgentName());
//					map.put("keyword2",agent.getAgentPhone());
//					map.put("remark","感谢你的使用。");
//					new SendTemplateMessage().sendTemplate(SendTemplateMessage.auditTemplateMessage , user.getOpenid() , map);
//				}
//			}


//			renderJson(apiResponse);
		}else{
			Agent agent = Agent.dao.findById(id);
			agent.setStatus(Agent.STATUS_FAil);
			boolean update = agent.update();
			if(update){
				WeixinUser user = WeixinUser.dao.findById(agent.getUserId());
				String unionid = user.getUnionid();
				WeixinUser weixinUser = WeixinUser.dao.findGZHUserByUnionId(unionid);
				if (weixinUser != null || weixinUser.getId() != null) {
					Map<String, String> map = new HashMap<>();
					String first = "由于提交注册经销商信息有误，请您认真核对注册信息并重新提交，中科易购将竭诚为您服务";
					map.put("first",first);
					map.put("keyword1",agent.getAgentName());
					map.put("keyword2",agent.getAgentPhone());
					map.put("remark","感谢你的使用。");
					new SendTemplateMessage().sendTemplate(SendTemplateMessage.auditTemplateMessage , user.getOpenid() , map);
				}
			}
			renderJson(new ApiResponse(update,update?"操作成功!":"操作失败!"));
		}
	}

	/**
	 * 修改折扣
	 */
	public void editDiscount(){
		String agentId = getPara("agent_id");
		if(StringUtil.isBlank(agentId)){
			fail("代理商id不能为空!");
			return;
		}
		String discountStr = getPara("discount");
		if(StringUtil.isBlank(discountStr)){
			fail("折扣不能为空!");
			return;
		}
		BigDecimal discount = new BigDecimal(0.00);
		try{
			discount = new BigDecimal(discountStr);
		}catch(NumberFormatException e){
			fail("折扣设置错误!");
			e.printStackTrace();
			return;
		}
		WeixinUser authUser = getAuthUser();
		Agent parentAgent = Agent.dao.findInfoByUserId(authUser.getId());


		if(!(discount.compareTo(new BigDecimal(0.00))>0&&discount.compareTo(new BigDecimal(1))<0)){
			fail("只能设置0~1之间的数字!");
			return;
		}



		Agent agent = Agent.dao.findById(agentId);
		if(agent==null){
			fail("代理商不存在!");
			return;
		}
		if(!agent.getParentId().equals(parentAgent.getId())){
			fail("代理商设置错误!不能设置别人的折扣!");
			return;
		}
		BigDecimal parentDiscount = new BigDecimal(0.00);
		if(Agent.TYPE_AREA.equals(parentAgent.getType())){
			List<AgentCity> agentCities = AgentCity.dao.findByAgentId(parentAgent.getId() , Agent.STATUS_SUCCESS);
			if(agentCities.size()>0){
				Integer levelId = agentCities.get(0).getLevelId();
				AgentLevel level = AgentLevel.dao.findById(levelId);
				if(level!=null){
					parentDiscount = level.getDiscount();
				}
			}
		}else {
			Integer levelId = parentAgent.getLevelId();
			AgentLevel level = AgentLevel.dao.findById(levelId);
			if(level!=null){
				parentDiscount = level.getDiscount();
			}else{
				parentDiscount = parentAgent.getDiscount()==null?new BigDecimal(0.00):parentAgent.getDiscount();
			}
		}

		if(parentDiscount.compareTo(discount)>=0){
			fail("折扣设置错误!不能超过自己!");
			return;
		}

		agent.setDiscount(discount);
		boolean update = agent.update();
		renderJson(new ApiResponse(update,update?"修改成功!":"修改失败!"));
	}


	/**
	 * 特约经销商提现操作
	 */
	public void authorizedDealerWithdrawal(){
		String price = getPara("price");
		String agentId = getPara("agent_id");
		WeixinUser authUser = getAuthUser();
		Integer userId = authUser.getId();
		String bankName = getPara("bank_name");
		String bankUserName = getPara("bank_user_name");
		String bankNum = getPara("bank_num");
		ApiResponse response = AgentService.dao.authorizedDealerWithdrawal(price , userId,bankName,bankUserName,bankNum,agentId);
		renderJson(response);
	}

	/**
	 * 获取这个代理商
	 * yue_profit 月盈利
	 * yue_count 月销售
	 * nian_profit 年盈利
	 * nian_count 年销售
	 * nian_user_count 年累积下单客户数
	 * auto：黎峻
	 */
	public void loadStatisticsData(){
		String agentId = getPara("agent_id");
		if(StringUtil.isBlank(agentId)){
			fail("代理商id不能为null!");
			return;
		}
		Agent agent = Agent.dao.findById(agentId);
		if(agent==null){
			fail("代理商不存在!");
			return;
		}
		Map<String,Object> map =new HashMap<>();
		//月盈利
		BigDecimal yue_profit= Db.queryBigDecimal("select  sum(price) from t_agent_account_log log where log.agent_id=?  AND log.status=1 and log.state=1  and   DATE_FORMAT(log.create_time,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m')  GROUP BY log.agent_id  ",agentId);
		if(yue_profit==null){
			yue_profit=BigDecimal.valueOf(0);
		}
		map.put("yue_profit",yue_profit);
		//月收入
		BigDecimal yue_count=Db.queryBigDecimal("select SUM(total_amount) FROM  t_order WHERE  DATE_FORMAT(receipt_time,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m')   and agent_id=? and state=3 ",agentId);
		if(yue_count==null){
			yue_count=BigDecimal.valueOf(0);
		}
		map.put("yue_count",yue_count);

		//年盈利select SUM(agent_cash_back)  FROM  t_order WHERE  YEAR(receipt_time) = YEAR(NOW())  and agent_id=? and state=3
		BigDecimal nian_profit=Db.queryBigDecimal("select  sum(price) from t_agent_account_log log where log.agent_id=?  AND log.status=1 and log.state=1 and  YEAR(log.create_time)=YEAR(NOW())  GROUP BY log.agent_id ",agentId);
		if(nian_profit==null){
			nian_profit=BigDecimal.valueOf(0);
		}
		map.put("nian_profit",nian_profit);
		//月收入
		BigDecimal nian_count=Db.queryBigDecimal("select SUM(total_amount) FROM  t_order WHERE  YEAR(receipt_time) = YEAR(NOW())   and agent_id=? and state=3",agentId);
		if(nian_count==null){
			nian_count=BigDecimal.valueOf(0);
		}
		map.put("nian_count",nian_count);
		map.put("nian_user_count",Db.queryLong("select  COUNT(distinct  user_id) FROM  t_order o WHERE  YEAR(o.receipt_time) = YEAR(NOW()) and o.agent_id=? and o.state=3 ",agentId));
		success(map);
	}



	/**
	 * 代理商支付定金
	 */
	public void payPrice(){
  		String agentId = getPara("agent_id");
		if(StringUtil.isBlank(agentId)){
			fail("代理商id不能为空!");
			return;
		}
		Integer payType = getParaToInt("payType");
		ApiResponse apiResponse = AgentService.dao.payPrice(agentId , getWxappId(),payType);
		renderJson(apiResponse);
	}


	/**
	 * 获取注册商品
	 * /xapp/agent/registerProduct
	 */
	public void registerProduct(){
		Products registerProduct = Products.dao.findRegisterProduct();
		List<Products> pro_list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
//		for (Object obj : data) {
//			JSONObject item = (JSONObject) obj;
			Products pro = registerProduct;
//			String sku_id = pro.getString("skuid");
			pro.put("num",2);
			pro.put("skuid", null);
			pro.put("sku", null);
			pro_list.add(pro);

//		}
		//初始化用户的地址
		UserAddress userAddress = UserAddress.dao.findByUserDefault(getAuthUserId());
		if (userAddress != null) {
			map.put("address", userAddress);
		} else {
			map.put("address", null);
		}
		map.put("pro_list", pro_list);
		map.put("register_order",1);
		success(map);
	}




}
